<?php

namespace app\api\controller;

use app\admin\model\OrderAfterSale;
use app\common\validate\OrderValidate;
use app\admin\model\Order as OrderMdl;
use app\admin\model\Orderitem;
use app\api\service\Order as OrderService;
use think\Db;
use think\Exception;
use think\Request;

class Order extends Base
{

    /**
     * // 用户在选择商品后，向API提交包含它所选择商品的相关信息
     * // API在接收到信息后，需要检查订单相关商品的库存量
     * // 有库存，把订单数据存入数据库中= 下单成功了，返回客户端消息，告诉客户端可以支付了
     * // 调用我们的支付接口，进行支付
     * // 还需要再次进行库存量检测
     * // 服务器这边就可以调用微信的支付接口进行支付
     * // 小程序根据服务器返回的结果拉起微信支付
     * // 微信会返回给我们一个支付的结果（异步）
     * // 成功：也需要进行库存量的检查
     * // 成功：进行库存量的扣除
     *
     * // 做一次库存量检测
     * // 创建订单
     * // 减库存--预扣除库存
     * // if pay 真正的减库存
     * // 在一定时间内30min没有去支付这个订单，我们需要还原库存
     *
     * // 在PHP里写一个定时器，每隔1min去遍历数据库，找到那些超时的
     * // 订单，把这些订单给还原库存
     * // linux crontab
     *
     * // 任务队列
     * // 订单任务加入到任务队列里
     * // redis
     *
     * //定时器，每隔1s，5s，访问API的接口
     * /
     *
     * /**
     * 创建订单
     */
    public function placeOrder(Request $request)
    {
        (new OrderValidate())->goCheck();
        $orderdata = $request->param();
        $products = $orderdata['products'];
        $uid = $orderdata['uid'];
        unset($orderdata['products']);
        $order = new OrderService();
        $result = $order->place($uid, $products, $orderdata);
        if (!$result['pass']) {
            return show(config('status.ERROR_STATUS'), '创建订单失败，库存不足', $result);
        } else {
            if (!$result['checkcoupon']) {
                return show(config('status.ERROR_STATUS'), '优惠券不可用', $result);
            }
            return show(config('status.SUCCESS_STATUS'), '创建订单成功', $result);
        }
    }

    /**
     * 用户订单确认收货
     */
    public function confirmReceiveGoods()
    {
        $param = self::getHttpParam();
        $info = $this->modifyState($param, 4);
        if (!$info) {
            return show(config('status.ERROR_STATUS'), '操作失败', []);
        }
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '确认成功');
    }

    /**
     * 取消未付款订单
     */
    public function cancelOrder()
    {
        $param = self::getHttpParam();
        $info = $this->modifyState($param, 5);
        if (!$info) {
            return show(config('status.ERROR_STATUS'), '操作失败', []);
        }
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '订单已取消');
    }

    private function modifyState($param, $status)
    {
        if (empty($param->orderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '订单ID(orderId) 不能为空');
        }

        Db::startTrans();
        try {
            $data = (array)$param;
            $model = new \app\admin\model\Order();

            if (!empty($param->orderId)) {
                $id = $param->orderId;
                $data['invalid_time'] = time();
                $data['status'] = $status;
                $model->allowField(true)->save($data, ['id' => $id]);
                Orderitem::where('order_id',$id)->update(['old_status'=>$status]);
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 售后列表
     */
    public function getRefundList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->account_number)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '用户账号 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'member_phone' => $param->account_number,
            'status' => [['=', 1], ['=', 2],['=',3], ['=', 4], ['=', 5], ['=', 6],['=',7], 'OR']
        ];
        $model = new OrderAfterSale();

        $fields = '*';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '未查到订单信息', '未查到订单信息');
        }
        $total = $model->where($where)->count();

        foreach ($list as $item) {
            $orderItems = Orderitem::where('id', $item->order_item_id)->find();
            $item['product'] = $orderItems;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 售后详情
     */
    public function getRefundDetails()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '订单ID不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new OrderAfterSale();

        $order = $model->where($where)->find();
        if (!$order) {
            return show(config('status.ERROR_STATUS'), '未查到订单信息', '未查到订单信息');
        }
        if (!empty($order->imgs)) {
            $order['imgs'] = explode(',', $order->imgs);
        }
        $orderItems = Orderitem::where('id', $order->order_item_id)->find();
        $order['product'] = $orderItems;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $order);
    }

    /**
     * 订单物流查询
     */
    public function getLogistics()
    {
        $param = self::getHttpParam();

        if (empty($param->express_no)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '运单号(express_no) 不能为空');
        }

        $where = [
            'express_no' => $param->express_no
        ];
        $model = new \app\common\model\ExpressTrace();
        $fields = '*';
        // 物流信息
        $item = $model->where($where)->field($fields)->find();
        if (!$item) {
            //return show(config('status.ERROR_STATUS'), '未查到物流信息', '未查到物流信息');
            $item = [];
            $item['express_no'] = $param->express_no;
            $order = OrderMdl::where('express_no', $param->express_no)->field('express_no, express_name')->find();
            // 快递公司
            $item['expressName'] = isset($order['express_name']) ? $order['express_name'] : '';

            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
        }

        $item['traces'] = json_decode($item['traces'], true);
        // 数组倒叙排序
        $item['traces'] = array_reverse($item['traces']);
        // 快递公司
        $item['expressName'] = \app\admin\model\Express::where('code', $item->shipper_code)->value('name');

        $orderId = OrderMdl::where('express_no', $item['express_no'])->value('id');
        $imgUrl = Orderitem::where('order_id', $orderId)->order('create_date desc')->value('product_img');
        $item['img_url'] = $imgUrl;

        // 是否从消息中心里进入
        if (!empty($param->logistics_mss_id)) {
            // 标记已读
            //db('message_logistics')->where('id', $param->logistics_mss_id)->update(['is_read' => 1]);
            db('message_logistics')->where('express_no', $param->express_no)->update(['is_read' => 1]);
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 订单列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '用户ID(memberId) 不能为空');
        }
//        if (empty($param->type)) {
//            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '订单类型(type) 不能为空');
//        }
//        if (!in_array($param->type, [1, 2])) {
//            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
//        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        // $uid = TokenService::getCurrentUid();
        $where = [
            'member_id' => $param->memberId
        ];
//        if ($param->type == 1) {
        // 线上订单
        $model = new OrderMdl();
        // 7=线下已完成订单，线下订单只有这一个状态
        if (!in_array($param->status, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '订单状态(status) 格式不正确');
        }
        if ($param->status == 0) {
            $where['status'] = [['=', 1], ['=', 2], ['=', 3], ['=', 4], ['=', 6],['=', 7],['=', 11],['=', 12],['=',13], 'OR'];
        } elseif($param->status == 2) {
            $where['status'] = [['=', 2], ['=', 11], 'OR'];
        }else{
            $where['status'] = $param->status;
        }

        $fields = 'id,order_no,total,total_count,status,create_date,invalid_time';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '未查到订单信息', '未查到订单信息');
        }
        $total = $model->where($where)->count();

        foreach ($list as &$item) {
            $orderItems = Orderitem::where('order_id', $item->id)->where('after_sale_status', 'in', [0,3,5])->order('create_date desc')->select();
            $item['products'] = $orderItems;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
//        } else {
//            // 门店订单 TODO
//            return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, [], 0);
//        }
    }

    /**
     * 订单详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();
        if (empty($param->orderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '订单ID(orderId) 不能为空');
        }
        $orderId = $param->orderId;
        $where = [
            'id' => $orderId
        ];
        $model = new OrderMdl();
        $fields = 'id,address_id,pickuppoint_id,discount_price,invoice_id,total,total_count,order_no,create_date,content,status,deliver_method,express_no,invalid_time';
        //$fields = "*";
        $item = $model->where($where)->field($fields)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), '未查到订单信息', '未查到订单信息');
        }
        $orderItems = Orderitem::where('order_id', $item->id)->order('create_date desc')->select();
        $item['discount_repurchase_price'] = 0;
        $item['discount_flashsale_price'] = 0;
        $item['discount_gift_price'] = 0;
        foreach ($orderItems as &$orderItem) {
            if($orderItem['is_repurchase'] == 1){
                $r_price = ($orderItem['price'] - intval($orderItem['repurchase_price'])) * $orderItem['count'];
                $item['discount_repurchase_price'] += $r_price;
            }
            if($orderItem['is_flashsale'] == 1){
                $f_price = ($orderItem['price'] - intval($orderItem['flashsale_price'])) * $orderItem['count'];
                $item['discount_flashsale_price'] += $f_price;
            }
            if(!empty($orderItem['gift_product_id'])){
                $g_Product = \app\admin\model\Product::where('id',$orderItem['gift_product_id'])->field('name,price')->find();
                $g_Product['count'] = $orderItem['gift_count'];
                $orderItem['gift_product'] = $g_Product;
                $g_price = $g_Product['price'] * $orderItem['gift_count'];
                $item['discount_gift_price'] += $g_price;
            }
        }
        $item['products'] = $orderItems;
        // 送货地址
        if ($item->address_id) {
            $address = \app\admin\model\Address::where('id', $item->address_id)->find();
            $item['address'] = $address;
        }
        // 自提地址
        if ($item->pickuppoint_id) {
            $pickuppoint = \app\admin\model\Pickuppoint::where('id', $item->pickuppoint_id)->find();
            $item['pickuppoint'] = $pickuppoint;
        }
        $invoice = \app\admin\model\Memberinvoice::where('id', $item->invoice_id)->find();
        if ($invoice) {
            $item['invoice'] = $invoice;
        }
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 获取首单立减金额
     * @param $memberid
     * @param $allproduct_price
     * @param int $type
     * @return int|string|\think\response\Json
     */
    public function getfirst_order_price($memberid,$allproduct_price,$type=1){
        $result = 0;
        $Member = \app\admin\model\Member::where('id',$memberid)->field('member_level_id,level_end_time,isfirst_order_reduce')->find();
        $Memberlevel = \app\admin\model\Memberlevel::where('id',$Member->member_level_id)->field('is_first_order,first_single_reduction')->find();
        if($Member->member_level_id !=1){
            $level_end_time = strtotime($Member->level_end_time);
            if($Member->isfirst_order_reduce == 0 && time() < $level_end_time){
                if($Memberlevel->is_first_order == 1){
                    $result = $allproduct_price*($Memberlevel->first_single_reduction / 100);
                }
            }
        }else{
            if($Member->isfirst_order_reduce == 0){
                if($Memberlevel->is_first_order == 1){
                    $result = $allproduct_price*($Memberlevel->first_single_reduction / 100);
                }
            }
        }
        $result = sprintf("%.2f",$result/100);
        if($type == 1){
            return show(config('status.SUCCESS_STATUS'),'ok',$result);
        }else{
            return $result;
        }
    }

}